<?php
class ProductController extends BackOfficeController
{
    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id)
    {
        $this->render('view', array(
            'model' => $this->api('Shop/Product/get', array('id' => $id)),
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate()
    {
        $this->actionUpdate();
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     *
     * @author HAU DAI
     */
    public function actionUpdate()
    {
        $subproduct = new SubProduct;
        $prices = array();
        if (Yii::app()->request->IsPostRequest) {
            //Save subproducts with post attributes
            if (isset($_POST['Price']) || isset($_POST['Subprovduct']) || isset($_POST['SalePrice']) || isset($_POST['ChargeShippingOption']) || isset($_POST['StockTotal'])) {
                foreach ($_POST['Id']['Subproduct'] as $item) {
                    $shipCost = str_replace(',', '', $_POST['ShipCost'][$item]);
                    SubProduct::model()->updateByPk($item, array('shipping_cost' => CPropertyValue::ensureInteger($shipCost)));
                    SubProduct::model()->updateByPk($item, array('stock_total' => CPropertyValue::ensureInteger($_POST['StockTotal'][$item])));
                    SubProduct::model()->updateByPk($item, array('charge_shipping_option' => CPropertyValue::ensureString($_POST['ChargeShippingOption'][$item])));
                    $price = str_replace(',', '', $_POST['Price'][$item]);
                    $salePrice = str_replace(',', '', $_POST['SalePrice'][$item]);
                    if ($price != '' && is_numeric($price) && is_numeric($salePrice)) {
                        $priceTemp = CPropertyValue::ensureFloat($price);
                        $salepriceTemp = CPropertyValue::ensureFloat($salePrice);
                        if ($salePrice == '' || ($priceTemp <= $salepriceTemp)) {
                            $salepriceTemp = $priceTemp;
                        }
                        SubproductPrice::model()->updateAll(array('price' => $priceTemp), 'sub_product_id=:subId', array(':subId' => $item));
                        SubproductPrice::model()->updateAll(array('sale_price' => $salepriceTemp), 'sub_product_id=:subId', array(':subId' => $item));
                    }
                    if (isset($_POST['sub-product-attribute_c0'])) {
                        foreach ($_POST['sub-product-attribute_c0'] as $attribute_group) {
                            if (isset($_POST['attribute_' . $attribute_group])) {
                                $command = Yii::app()->db->createCommand();
                                $attribute = $command->select('*')
                                    ->from(SITE_ID . '_shop_subproduct_attribute')
                                    ->where('subproduct_id=:subId AND group_id=:groupId', array(':subId' => $item, ':groupId' => $attribute_group))
                                    ->queryAll();
                                if (sizeof($attribute) > 0) {
                                    if ($_POST['attribute_' . $attribute_group][$item] != '') {
                                        $command->update(SITE_ID . '_shop_subproduct_attribute', array(
                                            'attribute_id' => $_POST['attribute_' . $attribute_group][$item],
                                        ), 'subproduct_id=:subId AND group_id=:groupId', array(':subId' => $item, ':groupId' => $attribute_group));
                                    } else {
                                        $command->delete(SITE_ID . '_shop_subproduct_attribute', 'subproduct_id=:subId AND group_id=:groupId', array(':subId' => $item, ':groupId' => $attribute_group));
                                    }

                                } else {
                                    if ($_POST['attribute_' . $attribute_group][$item] != '') {
                                        $command->insert(SITE_ID . '_shop_subproduct_attribute', array(
                                            'subproduct_id' => $item,
                                            'attribute_id' => $_POST['attribute_' . $attribute_group][$item],
                                            'group_id' => $attribute_group
                                        ));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (isset($_POST['Metadata'])) {
                $metaDataModel = $this->postModel('Metadata');
                $metaDataModel->data_name = 'Product Metadata';
                $metaDataModel = $this->api('Cms.Metadata.save', array('attributes' => $metaDataModel->attributes));
            }

            // save posted data
//            $model = $this->postModel('Product');
            $input = new XInputFilter($_POST['Product']);
            $model = $input->getModel('Product', array(
                'details1' => 'xss,notag,newline',
                'details2' => 'xss,notag,newline',
                'details3' => 'xss,notag,newline',
                'details4' => 'xss,notag,newline',
                'details5' => 'xss,notag,newline',
            ));
            if (isset($_POST['Metadata'])) {
                $model->metadata = $metaDataModel->id;
            }
            //fix up for the "/" in date string
            $result = $this->api('Shop.Product.save', array('input' => $model));
            if (!errorHandler()->hasErrors()) {
                $model = $result;

                //create first subproduct when create product
                if ($this->action->id == 'create') {
                    list($subproduct, $prices) = $this->createSubproduct($model);
                    // assign attributes for this new subproduct
                    if (!empty($subproduct->id)) {
                        $attrGroupsToAdd = array();
                        foreach ($_POST as $key => $val) {
                            if (stristr($key, 'attribute_')) {
                                if (!is_array($val)) {
                                    $val = (array)$val;
                                }
                                $group_id = str_replace('attribute_', '', $key);
                                // add attribute groups into array
                                $attrGroupsToAdd[] = $group_id;
                                // link attributes to sub-product
                                foreach ($val as $id) {
                                    $this->api('Shop.SubProduct.linkAttributes', array(
                                        'model_id' => $subproduct->id,
                                        'group_id' => $group_id,
                                        'attribute' => $val
                                    ));
                                }
                            }
                        }
                        $this->api('Shop.Product.linkAttributeGroup', array(
                            'model' => $model->id,
                            'attribute_groups' => $attrGroupsToAdd
                        ));
                    }
                }

                $this->api('Shop.Product.linkAllCategories', array('categories' => $this->post('categories', array()), 'model' => $model));

                //Link attribute group to product
                $this->linkAttributeGroup($model);
                //new product, create relationship product with required group
                if (!isset($_POST['Product']['id'])) {
                    $groups = isset($_POST['group']) ? array_keys($_POST['group']) : array();
                    if (count($groups)) {
                        $this->api('Shop.Product.linkGroups', array('id' => $model->id, 'groups' => $groups));
                    }
                }
                $this->linkAttrs($model->id);

                $this->message = Yii::t('Xpress.Common', 'Item has been saved successfully.');
                if ($this->action->id == 'create') {
                    //open new tab
                    cs()->registerScript(__CLASS__ . 'UpdateProduct', "parent.App.newTab('" . $this->createUrl('/Shop/admin/product/update', array('id' => $model->id)) . "');");
                    //close this tab
                    cs()->registerScript(__CLASS__ . 'CloseCreate', "parent.App.closeTab('" . $this->createUrl('/Shop/admin/product/create') . "');");
                }
                //$this->redirect($this->createUrl('update', array('id' => $model->id)));
            } elseif ($this->action->id == 'create') {
                list($subproduct, $prices) = $this->createSubproduct($model, true);
            }
        } else {
            // show edit form
            if (($id = $this->get('id', 0)) > 0) {
                $model = $this->api('Shop.Product.get', array('id' => $id));
            }
            if (!isset($model) || !$model instanceof Product) {
                $model = new Product();
                list($subproduct, $prices) = $this->createSubproduct($model);
            }
        }

        $metaDataModel = NULL;
        if (!isset($metaDataModel)) {
            if ($model->metadata != NULL) {
                $metaDataModel = Metadata::model()->findByPk($model->metadata);
            }
            if (!is_object($metaDataModel)) {
                $metaDataModel = new Metadata();
            }
        }

        $subProductModel = NULL;
        if (!is_null($model) && !$model->isNewRecord) {
            $subProductModel = $this->adminSubproduct($model->id);
        }

        //Search all subproducts match the createrias
        $criteria = new CDbCriteria();
        $criteria->compare('t.product_id', $model->id);
        if (isset($_GET['subproduct_id']) && !empty($_GET['subproduct_id'])) {
            $criteria->compare('t.id', CPropertyValue::ensureInteger($_GET['subproduct_id']));
        }
        if (isset($_GET['subproduct_sku']) && !empty($_GET['subproduct_sku'])) {
            $criteria->addSearchCondition('t.sku', CPropertyValue::ensureString($_GET['subproduct_sku']), true, 'AND', 'ILIKE');
        }
        if (isset($_GET['subproduct_stock_total']) && !empty($_GET['subproduct_stock_total'])) {
            $criteria->compare('t.stock_total', CPropertyValue::ensureInteger($_GET['subproduct_stock_total']));
        }
        if (isset($_GET['subproduct_stock_reserved']) && !empty($_GET['subproduct_stock_reserved'])) {
            $criteria->compare('t.stock_reserved', CPropertyValue::ensureInteger($_GET['subproduct_stock_reserved']));
        }
        if (isset($_GET['subproduct_charge_shipping_option']) && $_GET['subproduct_charge_shipping_option'] != '') {
            $criteria->addSearchCondition('t.charge_shipping_option', $_GET['subproduct_charge_shipping_option'], true, 'AND', 'ILIKE');
        }
        if (isset($_GET['status']) && $_GET['status'] != '') {
            $criteria->addCondition('t.status = ' . ($_GET['status'] ? 'true' : 'false'));
        }
        $criteria->join = 'LEFT JOIN ' . SITE_ID . '_shop_subproduct_attribute attr' . ' ON attr.subproduct_id = t.id';
        $criteria->together = true;
        if (isset($_GET['attributesSub']) && sizeof($_GET['attributesSub']) > 0) {
            foreach ($_GET['attributesSub'] as $attributeSub)
                $criteria->compare('attr.attribute_id', $attributeSub);
        }
        $criteria->distinct = true;
        $criteria->order = 't.creation_datetime DESC';
        //Create CActiveDataProvider for subproducts match the criterias
        $subproductProvider = new CActiveDataProvider('SubProduct', array(
            'pagination' => array(
                'pageSize' => 20,
            ), 'criteria' => $criteria
        ));
        //Get subproduct infos
        $subsInfo = array();
        foreach ($subproductProvider->getData() as $sub) {
            $subsInfo['id'][] = $sub->id;
            $subsInfo[$sub->id]['sku'] = '\'' . $sub->sku . '\'';
        }
        //Render page
        $this->render('update', array(
            'model' => $model,
            'metaDataModel' => $metaDataModel,
            'subproduct' => $subproduct,
            'prices' => $prices,
            'subProductModel' => $subProductModel,
            'subproductProvider' => $subproductProvider,
            'subsInfo' => $subsInfo
        ));
    }

    protected function adminSubproduct($productId)
    {
        $model = new SubProduct('search');
        $model->unsetAttributes(); // clear any default values
        if (isset($_GET['SubProduct'])) {
            $model->attributes = $_GET['SubProduct'];
        }
        $model->product_id = $productId;

        return $model;
    }

    protected function createSubproduct($product, $onlyValidate = false)
    {
        $model = new SubProduct;
        if (isset($_POST['SubproductPrice'])) {
            if ($onlyValidate) {
                $model = $this->postModel('SubProduct');
            } else {
                $_POST['SubProduct']['product_id'] = $product->id;
                $model = $this->postModel('SubProduct');
                if (empty($model->shipping_cost)) {
                    $model->shipping_cost = 0;
                }
                $model->status = true;
                $result = $this->api('Shop.SubProduct.save', array('input' => $model));
                if (is_object($result)) {
                    $model = $result;
                }
            }
        }
        $prices = $this->createPrices($model, $onlyValidate);

        return array(
            $model,
            $prices,
        );
    }

    /**
     * @param SubProduct $subproduct
     * @return array SubproductPrice
     */
    protected function createPrices($subproduct, $onlyValidate = false)
    {
        $criteria = new CDbCriteria;
        $criteria->order = 'name';
        $levels = PriceLevel::model()->findAll($criteria);
        $items = array();
        if (count($levels)) {
            /** @var $level PriceLevel */
            foreach ($levels as $level) {
                $model = new SubproductPrice();
                $model->attachBehavior('CTimestampBehavior', array(
                    'class' => 'zii.behaviors.CTimestampBehavior',
                    'timestampExpression' => 'date("Y-m-d H:i:s")',
                    'createAttribute' => 'date_created',
                    'updateAttribute' => 'date_updated',
                ));

                //store price_level name for show
                $model->id = $level->name;
                $model->price_level_id = $level->id;
                $model->sub_product_id = $subproduct->id;
                $items[] = $model;
            }
        }
        if (isset($_POST['SubproductPrice'])) {
            foreach ($items as $i => $item) {
                if (isset($_POST['SubproductPrice'][$i])) {
                    $item->attributes = $_POST['SubproductPrice'][$i];
                }
                if ($onlyValidate) {
                    $item->validate();
                    $items[$i] = $item;
                    continue;
                }
                //clear price_level name before save
                $item->id = NULL;
                $item->setIsNewRecord(true);
                $model->sub_product_id = $subproduct->id;
                if (!$item->save()) {
                    Yii::log(CVarDumper::dumpAsString($item->getErrors()), CLogger::LEVEL_ERROR);
                }
            }
        }

        return $items;
    }


    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id)
    {
        if (Yii::app()->request->isPostRequest) {
            // we only allow deletion via POST request
            if (($id = $this->get('id', NULL)) !== NULL) {
                $ids = is_numeric($id) ? array($id) : explode(',', $id);
                $count = count($ids);
                if ($count > 0) {
                    $unDelete = array();
                    foreach ($ids as $id) {
                        $hasOrder = $this->api('Shop.Product.hasOrder', array('id' => $id));
                        if ($hasOrder) {
                            if ($count == 1) {
                                echo CJSON::encode(array(
                                    'error' => true,
                                    'msg' => 'This Product is can not delete because there are orders related to it.',
                                ));
                                Yii::app()->end();
                            } else {
                                $unDelete[] = $id;
                            }
                        }
                    }
                    $ids = array_diff($ids, $unDelete);
                }

                // delete one or multiple objects given the list of object IDs
                $result = $this->api('Shop.Product.delete', array('ids' => $ids));
                if (!errorHandler()->hasErrors()) {
                    //delete all subproduct
                    $this->api('Shop.SubProduct.deleteBy', array('productId' => $ids));

                    // only redirect user to the admin page if it is not an AJAX request
                    if (!Yii::app()->request->isAjaxRequest) {
                        $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
                    } else {
                        echo CJSON::encode(array('msg' => Yii::t('Xpress.Common', 'Items are deleted successfully.')));
                    }
                } else {
                    // redirecting with error carried to the redirected page
                    if (!Yii::app()->request->isAjaxRequest) {
                        Product()->setFlashErrors(errorHander()->getErrors());
                        $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
                    } else {
                        echo implode("\n", errorHandler()->getErrorMessages());
                    }
                }
            } else {
                throw new CHttpException(400, Yii::t('Xpress.Common', 'Cannot delete item with the given ID.'));
            }
        } else {
            throw new CHttpException(400, Yii::t('Xpress.Common', 'Invalid request. Please do not repeat this request again.'));
        }
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $this->actionAdmin();
    }

    /**
     * Manages all models.
     */
    public function actionAdmin()
    {
        //category tree
        $categories = ProductCategory::model()->findAll();
        app()->XService->run('Xpress.NestedCategory.buildTree', array('data' => $categories));
        $data = app()->XService->run('Xpress.NestedCategory.findTree', array('className' => 'ProductCategory'));
        //normalize data for dropdown
        $categories = array();
        $this->normalizeCategory($data, $categories);

        $criteria = new CDbCriteria();
        if (isset($_GET['name']) && !empty($_GET['name'])) {
            $criteria->addSearchCondition('t.name', CPropertyValue::ensureString($_GET['name']), true, 'AND', 'ILIKE');
        }
        if (isset($_GET['custom_url']) && !empty($_GET['custom_url'])) {
            $criteria->addSearchCondition('t.custom_url', CPropertyValue::ensureString($_GET['custom_url']), true, 'AND', 'ILIKE');
        }
        if (isset($_GET['category']) && !empty($_GET['category'])) {
            $categoryId = CPropertyValue::ensureInteger($_GET['category']);
            $rows = app()->XService->run('Xpress.NestedCategory.findTree', array('className' => 'ProductCategory', 'id' => $categoryId, 'includeRoot' => false));
            $criteria->with = array('categories' => array('select' => false, 'together' => true));
            if (is_array($rows) && count($rows)) {
                $items = array();
                $this->normalizeCategory($rows, $items);
                if (is_array($items) && count($items)) {
                    $items = array_keys($items);
                }
                $items[] = $categoryId;
                $criteria->addInCondition('categories.id', $items);
            } else {
                $criteria->compare('categories.id', $categoryId);
            }
        }
        //Filter for default SKU
        if (isset($_GET['default_sku']) && !empty($_GET['default_sku'])) {
            $subproducts = SubProduct::model()->findAll("sku LIKE :sku", array(':sku' => "%" . $_GET['default_sku'] . "%"));
            $subIds = array();
            foreach ($subproducts as $subproduct) {
                $subIds[] = $subproduct->id;
            }
            if (count($subIds) > 0) {
                $criteria->addCondition('t.sub_default IN (' . implode(',', $subIds) . ')');
            }else{
                $criteria->addCondition('false');
            }
        }
        if (isset($_GET['status']) && $_GET['status'] != '') {
            $criteria->addCondition('t.status = ' . ($_GET['status'] ? 'true' : 'false'));
        }

        $dataProvider = new CActiveDataProvider('Product', array(
            'sort' => array(
                'defaultOrder' => 't.id DESC',
            ),
            'pagination' => array(
                'pageSize' => defined('SETTINGS_BO_PAGE_SIZE') ? SETTINGS_BO_PAGE_SIZE : 20,
            ),
            'criteria' => $criteria,
        ));
        $this->render('admin', array(
            'dataProvider' => $dataProvider,
            'categories' => $categories,
        ));
    }

    protected function normalizeCategory($data, &$categories = array())
    {
        if (is_array($data) && count($data)) {
            foreach ($data as $row) {
                $categories[$row['id']] = str_repeat('--', $row['level']) . $row['title'];
                if (isset($row['children']) && is_array($row['children']) && count($row['children'])) {
                    $this->normalizeCategory($row['children'], $categories);
                }
            }
        }
    }

    /*
     * Ths function is use for quick assign product to category     *
     */
    public function actionAssignCategory()
    {
        $category_id = $this->get('category-id-filter', NULL);
        //find all child categories

        $criteria = new CDbCriteria();

        if (!empty($category_id)) {
            $cat_criteria = new CDbCriteria();
            //$cat_criteria->select = false;
            //$cat_criteria->together = true;
            //todo need to review later
            $cat_ids = array();
            $child_cats = ProductCategory::model()->findAll('parent_id=:parent_id and status=:status', array(':parent_id' => $category_id, ':status' => true));
            foreach ($child_cats as $cat) {
                $cat_ids[] = $cat->id;
            }
            $cat_criteria->addInCondition('categories.id', $cat_ids);
            $criteria->with = array(
                'categories' => array(
                    'joinType' => 'INNER JOIN',
                    'select' => false,
                    'together' => true,
                    'condition' => 'categories.id IN ' . '(' . implode(',', $cat_ids) . ')',
                )
            );
        }
        $name_filter = $this->get('name-filter', NULL);
        if ($name_filter != NULL) {
            $criteria->addSearchCondition('name', $name_filter, true, 'AND', 'ILIKE');
        }

        $status_filter = $this->get('product-status-filter', NULL);
        if ($status_filter !== NULL) {
            $criteria->compare('t.status', $status_filter);
        }
        //Filter the on sale
        $on_sale_filter = $this->get('on-sale-filter', NULL);
        if ($on_sale_filter !== NULL && CPropertyValue::ensureBoolean($on_sale_filter)) {
            //
            $criteria->compare('on_sale', true);
            //Get the date start and date end
            $date_start_filter = $this->get('start-date-filter', NULL);
            $date_end_filter = $this->get('end-date-filter', NULL);
            if (!empty($date_start_filter)) {
                $criteria->addCondition("on_sale_start >= '" . date('Y-m-d', strtotime($date_start_filter)) . "'");
            }
            if (!empty($date_end_filter)) {
                $criteria->addCondition("on_sale_end <= '" . date('Y-m-d', strtotime($date_end_filter)) . "'");
            }
        }
        $dataProvider = new CActiveDataProvider('Product', array(
            'criteria' => $criteria,
            'pagination' => array(
                'pageSize' => 40
            )
        ));
        $topCategory = CHtml::listData(ProductCategory::model()->findAll('parent_id=:parent_id AND status=:status', array(':parent_id' => 0, ':status' => true)), 'id', 'title');
        $this->render('assign', array('dataProvider' => $dataProvider, 'topCat' => $topCategory));
    }

    public function actionAssign()
    {
        $product_id = $this->post('product_id', NULL);
        $category_id = $this->post('category_id', NULL);
        if (!is_null($product_id) && !is_null($category_id)) {
            $this->api('Shop.Product.linkCategory', array(
                'product_id' => $product_id,
                'category_id' => $category_id
            ));
        }
    }

    public function actionGetSecondCategories()
    {
        $product_id = $this->post('product_id', NULL);
        $category_id = $this->post('category_id', NULL);
        $data = array();
        if (!is_null($product_id) && !is_null($category_id)) {
            $criteria = new CDbCriteria();
            $criteria->addNotInCondition('product.id', array($product_id));
            $data = CHtml::listData(ProductCategory::model()
                /*->with(
                array(
                    'products' => array(
                        'criteria' => $criteria,
                        'together' => true
                    ),
                )
            )*/
                ->findAll('parent_id=:parent_id AND status=:status', array(':parent_id' => $category_id, ':status' => true)), 'id', 'title');
            //CHtml::listData(ProductCategory::model()->findAll('parent_id=:parent_id', array(':parent_id' => $category_id)), 'id', 'title');
        }
        echo CJSON::encode($data);
    }

    public function actionUnassign()
    {
        $product_id = $this->post('product_id', NULL);
        $category_id = $this->post('category_id', NULL);
        if (!is_null($product_id) && !is_null($category_id)) {
            $this->api('Shop.Product.unLinkCategory', array(
                'product_id' => $product_id,
                'category_id' => $category_id
            ));
        }
    }

    public function getCategoryForFilter()
    {
        $data = array();
        $top = CHtml::listData(ProductCategory::model()->findAll('parent_id=:parent_id AND status=:status', array(':parent_id' => 2, ':status' => true)), 'id', 'title');

        /*foreach ($top as $key => $value) {
            $categories = ProductCategory::model()->findAll('parent_id=:parent_id', array(':parent_id' => $key));
            $data[$value] = CHtml::listData($categories, 'id', 'title');
        }*/

        return $top;
    }

    public function getCategoriesForUpdate($model = NULL)
    {
        //Get the raw list
        $data = array();
        $top = CHtml::listData(ProductCategory::model()->findAll('parent_id=:parent_id AND status=:status', array(':parent_id' => 0, ':status' => true)), 'id', 'title');
        foreach ($top as $key => $value) {
            $categories = ProductCategory::model()->findAll('parent_id=:parent_id AND status=:status', array(':parent_id' => $key, ':status' => true));
            $cats = array();
            foreach ($categories as $cat) {
                $cats[$cat->id] = html_entity_decode($cat->title, ENT_COMPAT, 'UTF-8');
            }
            $value = html_entity_decode($value, ENT_COMPAT, 'UTF-8');
            $data[$value] = $cats;
        }
        //Get the selected array
        $selected = array();
        if (is_object($model)) {
            $selected = CHtml::listData($model->categories, 'id', 'title');
        }
        //flip the array to get the id of select become value
        $selected = array_flip($selected);

        return array('data' => $data, 'selected' => $selected);
    }

    public function actionExport()
    {
        if (app()->request->isPostRequest) {
            $export_ext = isset($_POST['export-to-excel']) ? 'excel' : 'pdf';
            $res = $this->api('Shop.Product.export', array('type' => $this->post('exportType', 'all'), 'extension' => $export_ext));
        }
        //$this->redirect($url);
    }

    public function actionGalleries()
    {
        $galleries = $this->api('Gallery.Gallery.list');

        header('Cache-Control: no-cache, must-revalidate');
        header('Content-type: application/json');
        echo $_GET['callback'] . '(' . CJavaScript::jsonEncode($galleries) . ');';
        Yii::app()->end();
    }

    public function getAttributeGroups()
    {
        $criteria = new CDbCriteria();
        $criteria->compare('t.is_sub', true);
        $criteria->compare('t.status', true);
        $criteria->with = array('attr' => array(
            'joinType' => 'INNER JOIN',
            'together' => true,
            'select' => false,
        )
        );
        $dataProvider = new CActiveDataProvider('AttributeGroup', array(
            'criteria' => $criteria,
            'pagination' => false
        ));

        return $dataProvider;
    }

    private function linkAttributeGroup($model)
    {
        $attribute_groups = array();
        if (isset($_POST['sub-product-attribute_c0'])) {
            $attribute_groups = $this->post('sub-product-attribute_c0');
        } else {
            //todo will run a loop through the $_POST and filter to get the right
        }
        $this->api('Shop.Product.linkAttributeGroup', array(
            'model' => $model->id,
            'attribute_groups' => $attribute_groups
        ));
    }

    public function actionAssignGroups($id)
    {
        $model = $this->api('Shop.Product.get', array('id' => $id));

        if (!is_object($model)) {
            throw new CHttpException(404, 'Product not found');
        }

        $criteria = new CDbCriteria;
        $criteria->addCondition('t.status = true AND t.is_sub = false');
        $criteria->with = array('attr' => array(
            'joinType' => 'INNER JOIN',
            'together' => true,
            'select' => false,
        ));
//        $criteria->distinct = true;
        $criteria->order = 'trim(t.name)';
        $groups = AttributeGroup::model()->findAll($criteria);
        if (count($groups)) {
            $groups = CHtml::listData($groups, 'id', 'name');
        }

        $criteria->order = 'pag.ordering, trim(t.name)';
        $criteria->join = 'INNER JOIN ' . SITE_ID . '_shop_product_attribute_group pag ON pag.attribute_group_id = t.id';
        $criteria->compare('pag.product_id', $id);
        $selected = AttributeGroup::model()->findAll($criteria);
        if (count($selected)) {
            $selected = array_flip(CHtml::listData($selected, 'id', 'name'));
        }
        //display attrs by ordering
        //first, get all attrs selected is be order by ordering in group
        //and append attrs not selected
        $selectedArr = array_flip($selected);
        $diff = array_diff_key($groups, $selectedArr);
        $groups = CMap::mergeArray($selectedArr, $diff);

        $this->render('assign_attributes', array(
            'groups' => $groups,
            'model' => $model,
            'selected' => $selected,
        ));
    }

    public function getAttributes($product)
    {
        if (!is_object($product)) {
            return array();
        }

        //build the attribute array
        $attribute_data = array();
        if ($product->isNewRecord) {
            $attribute_groups = AttributeGroup::model()->findAllByAttributes(array(
                'is_sub' => false,
                'status' => true,
                //'required'=>true,
            ));
        } else {
            $attribute_groups = AttributeGroup::model()->findAllBySql('
            select * from ' . SITE_ID . '_shop_attribute_group "g"
            LEFT JOIN ' . SITE_ID . '_shop_product_attribute_group "pg" ON "g".id="pg".attribute_group_id
            where "pg".product_id=:product_id AND "pg".status=:status AND is_sub = false AND g.status=true', array(
                    ':product_id' => $product->id,
                    ':status' => true
                ));
        }
        if (is_array($attribute_groups) && count($attribute_groups)) {
            foreach ($attribute_groups as $group) {
                $attributes = $group->attr(array(
                    'condition' => 'status=:status',
                    'params' => array(
                        ':status' => true
                    ),
                    'order' => "attr.ordering, trim(name)",
                ));
                if (is_array($attributes) && count($attributes)) {
                    $attribute_data[$group->id] = array(
                        'name' => $group->name,
                        'type' => $group->type,
                        'data' => CHtml::listData($attributes, 'id', 'name'),
                        'required' => $group->required
                    );
                }
            }
        }

        return $attribute_data;
    }

    public function findSelected($model, $group_id)
    {
        $command = Yii::app()->db->createCommand();
        $rows = $command->select('attribute_id')
            ->from(SITE_ID . '_shop_product_attribute')
            ->where('product_id=:product_id AND group_id=:group_id', array(
                ':product_id' => $model->id,
                'group_id' => $group_id
            ))->queryAll();
        $selected = array();
        if (is_array($rows) && count($rows)) {
            foreach ($rows as $row) {
                foreach ($row as $value)
                    $selected[] = $value;
            }
        }

        return $selected;
    }

    protected function linkAttrs($productId)
    {
        if (isset($_POST['group']) && is_array($_POST['group'])) {

            /** @var $command CDbCommand */
            $command = Yii::app()->db->createCommand();
            $command->delete(SITE_ID . '_shop_product_attribute',
                'product_id=:product_id',
                array(':product_id' => $productId)
            );
            foreach ($_POST['group'] as $groupId => $value) {
                if (!is_array($value)) {
                    if (empty($value)) {
                        continue;
                    }
                    $value = array($value);
                }
                foreach ($value as $val) {
                    //insert
                    $command = Yii::app()->db->createCommand();
                    $command->insert(SITE_ID . '_shop_product_attribute', array(
                        'product_id' => $productId,
                        'attribute_id' => $val,
                        'group_id' => $groupId,
                    ));
                }
            }
        }
    }

    protected function previewUrl($model)
    {
        $previewUrl = defined("SHOP_PRODUCT_PREVIEW_URL") ? SHOP_PRODUCT_PREVIEW_URL : "/product-[sku].html";

        $popupData = array();

        //find alias from Shop module match with [sku] param
        if (method_exists(Yii::app()->getModule('Shop'), 'getPages')) {
            $pages = Yii::app()->getModule('Shop')->getPages();
            if (is_array($pages) && count($pages)) {
                $matchAlias = '';
                foreach ($pages as $alias => $config) {
                    if (isset($config['urls']) && is_array($config['urls'])) {
                        foreach ($config['urls'] as $url) {
                            $url = preg_replace('/\[(\w+):?.*?\]/', '[$1]', $url);
                            if (preg_match_all('/\[(\w+)\]/', $url, $matches)) {
                                if (isset($matches[1]) && count($matches[1]) == 1 && in_array('sku', $matches[1])) {
                                    $previewUrl = $url;
                                    $matchAlias = $alias;
                                    break;
                                }
                            }
                        }
                    }
                    if (!empty($matchAlias)) {
                        break;
                    }
                }
            }

            //find all pages and urls by alias
            //must choose page when preview
            if (!empty($matchAlias)) {
                $criteria = new CDbCriteria;
                $criteria->with = array('page');
                $criteria->compare('t.status', true);
                $criteria->compare('page.status', true);
                $criteria->compare('page.alias', $matchAlias);
                $pageUrls = PageUrl::model()->findAll($criteria);
                $uniqueUrls = array();
                /** @var $pageUrl PageUrl */
                foreach ($pageUrls as $pageUrl) {
                    $url = preg_replace('/\[(\w+):?.*?\]/', '[$1]', $url);
                    if (preg_match_all('/\[(\w+)\]/', $url, $matches)) {
                        if (isset($matches[1]) && count($matches[1]) == 1 && in_array('sku', $matches[1])) {
                            if (in_array($pageUrl->page_id . ':' . $url, $uniqueUrls)) {
                                continue;
                            }
                            $uniqueUrls[] = $pageUrl->page_id . ':' . $url;

                            $previewUrl = $url;
                            if (!isset($popupData[$pageUrl->page_id])) {
                                $popupData[$pageUrl->page_id] = array(
                                    'value' => $pageUrl->page_id,
                                    'label' => $pageUrl->page->title,
                                    'urls' => array($pageUrl->id => array(
                                        'value' => $pageUrl->id,
                                        'label' => $url,
                                    )),
                                );
                            } else {
                                $popupData[$pageUrl->page_id]['urls'][$pageUrl->id] = array(
                                    'value' => $pageUrl->id,
                                    'label' => $url,
                                );
                            }
                        }
                    }
                }
            }
        }

        //generate correct url
        if ($model instanceof SubProduct) {
            $subProduct = $model;
        } else {
            $subProduct = $model->getCurrentSubproduct(true, true);
        }
        if (!is_object($subProduct)) {
            return "#";
        } else {
            //if only one url match => go preview
            //if not show popup choose url for preview
            //generate correct url
            if (count($popupData) > 1) {
                $getPreviewUrl = $this->createUrl('previewUrl');
                $popupData = CJavaScript::encode($popupData);
                $js = <<<EOP
$.popup_data = $popupData;
$.popup_data_subproduct_id = '';
$.popup_data_page_id = '';
$.popup_data_page_url_id = '';
$('body').delegate('.button-column .preview','click',function(){
    var subproduct_id = $(this).attr('href');
    $.popup_data_subproduct_id = parseInt(subproduct_id.replace('#',''));

    //set pages dropdown
    $('#preview-options-modal .preview-option-page').html('');
    $.each($.popup_data, function(page_id,item){
        $('#preview-options-modal .preview-option-page')
            .append('<option value="'+item.value+'">'+item.label+'</option>');
    });
    $.popup_data_page_id = $('#preview-options-modal .preview-option-page').val();

    //set urls dropdown
    $('#preview-options-modal .preview-option-url').html('');
    if ($.popup_data[$.popup_data_page_id] != undefined)
    {
        $.each($.popup_data[$.popup_data_page_id]['urls'], function(page_url_id,item){
            $('#preview-options-modal .preview-option-url')
                .append('<option value="'+item.value+'">'+item.label+'</option>');
        });
    }
    $.popup_data_page_url_id = $('#preview-options-modal .preview-option-url').val();
    $('#preview-options-modal .preview-option-url').trigger('change');

    //hide preview button
    $('#preview-options-modal .btn-primary').attr('href','#').hide();

    //show popup
    $('#preview-options-modal').modal('show');
    return false;
});
$('body').delegate('#preview-options-modal .preview-option-page, #preview-options-modal .preview-option-url','change',function(){
    $.popup_data_page_id = $('#preview-options-modal .preview-option-page').val();
    $.popup_data_page_url_id = $('#preview-options-modal .preview-option-url').val();

    if ($.popup_data[$.popup_data_page_id] != undefined
        && $.popup_data[$.popup_data_page_id]['urls'][$.popup_data_page_url_id] != undefined)
    {
        parent.$('#ajax-loading').show();
        var item = $.popup_data[$.popup_data_page_id]['urls'][$.popup_data_page_url_id];
        //get url by category id and url pattern
        $.get('$getPreviewUrl',{
            url : item.label,
            id : $.popup_data_subproduct_id
        },function(url){
            $('#preview-options-modal .btn-primary').attr('href',url).show();
            parent.$('#ajax-loading').hide();
        });
    }
});
EOP;
                cs()->registerScript(__CLASS__ . 'PreviewChooseUrl', $js);

                return '#' . $subProduct->id;
            } else {
                return $this->buildPreviewUrl($subProduct, $previewUrl);
            }
        }
    }

    /**
     * @param Category $model
     * @param $previewUrl url pattern
     * @return string
     */
    protected function buildPreviewUrl($subProduct, $previewUrl)
    {
        $host = defined('SHOP_PREVIEW_HOST') ? SHOP_PREVIEW_HOST : Yii::app()->request->hostInfo;
        $previewUrl = str_replace(array('[sku]', '<sku>'), $subProduct->sku, $previewUrl);
        if (strpos($previewUrl, '?') === false) {
            $previewUrl .= '?';
        } else {
            $previewUrl .= '&';
        }
        $previewUrl .= 'product_preview=1';

        return rtrim($host, '/') . '/' . ltrim($previewUrl, '/');
    }

    /**
     * @param $url page url preview
     * @param $id category id
     */
    public function actionPreviewUrl($url, $id)
    {
        $model = SubProduct::model()->findByPk($id);
        if (is_object($model)) {
            echo $this->buildPreviewUrl($model, $url);
        }
    }

    public function actionOutOfStockProductsReport()
    {
        $model = new Product('search');
        $model->unsetAttributes(); // clear any default values
        $model->status = '1';
        $model->in_stock = '0';

        if (isset($_GET['Product'])) {
            $model->attributes = $_GET['Product'];
        }

        $this->render('out_of_stock_products_report', array(
            'model' => $model,
        ));
    }

    public function actionExportOutOfStockProductsReport()
    {
        if (app()->request->isPostRequest) {
            $export_type = isset($_POST['export-to-excel']) ? 'excel' : 'pdf';
            $data = array();
            $limit = 100;
            $stop = false;
            $offset = 0;
            while ($stop == false) {
                $sql = 'SELECT t.id, t.name FROM "' . SITE_ID . '_shop_product" "t" WHERE t.status = true AND t.in_stock = false ORDER BY t.id DESC LIMIT ' . $limit . ' OFFSET ' . $offset;
                $products = app()->db->createCommand($sql)->queryAll();
                if (!is_array($products) || count($products) <= 0) {
                    $stop = true;
                } else {
                    foreach ($products as $product) {
                        $row = array();
                        // get categories of this product
                        $cats = array();
                        $cat_sql = '
                        SELECT c.title FROM "' . SITE_ID . '_shop_category" "c"
                        INNER JOIN "' . SITE_ID . '_shop_product_category" "pc" ON pc.category_id = c.id
                        WHERE pc.product_id = ' . $product['id'];
                        $cats_rows = app()->db->createCommand($cat_sql)->queryAll();
                        if (is_array($cats_rows) && count($cats_rows) > 0) {
                            foreach ($cats_rows as $cat_row) {
                                $cats[] = $cat_row['title'];
                            }
                        }
                        if ($export_type == 'excel') {
                            $row['A'] = implode(', ', $cats);
                            // name
                            $row['B'] = $product['name'];
                        } elseif ($export_type == 'pdf') {
                            $row['cats'] = implode(', ', $cats);
                            // name
                            $row['name'] = $product['name'];
                        }
                        // get sub products of this product for sku, stock
                        $sku_str = $stock_total_str = $stock_reserved_str = '';
                        $sub_sql = 'SELECT sku, stock_total, stock_reserved FROM "' . SITE_ID . '_shop_subproduct" WHERE product_id = ' . $product['id'];
                        $sub_rows = app()->db->createCommand($sub_sql)->queryAll();
                        if (is_array($sub_rows) && count($sub_rows) > 0) {
                            foreach ($sub_rows as $sub_row) {
                                if ($export_type == 'excel') {
                                    $sku_str .= $sub_row['sku'] . "\n";
                                } else {
                                    $sku_str .= '<p>' . $sub_row['sku'] . '</p>';
                                }
                                $stock_total = intval($sub_row['stock_total']);
                                $stock_reserved = intval($sub_row['stock_reserved']);
                                if ($export_type == 'excel') {
                                    $stock_total_str .= $stock_total . "\n";
                                } else {
                                    $stock_total_str .= '<p>' . $stock_total . '</p>';
                                }
                                if ($export_type == 'excel') {
                                    $stock_reserved_str .= $stock_reserved . "\n";
                                } else {
                                    $stock_reserved_str .= '<p>' . $stock_reserved . '</p>';
                                }
                            }
                        }
                        if ($export_type == 'excel') {
                            $row['C'] = $sku_str;
                            $row['D'] = $stock_total_str;
                            $row['E'] = $stock_reserved_str;
                        } elseif ($export_type == 'pdf') {
                            $row['sku'] = $sku_str;
                            $row['stock_total'] = $stock_total_str;
                            $row['stock_reserved'] = $stock_reserved_str;
                        }
                        $data[] = $row;
                    }
                }
                $offset = $offset + $limit;
            }
            // export
            if ($export_type == 'excel') {
                $columns = array(
                    array('index' => 'A', 'name' => 'Categories'),
                    array('index' => 'B', 'name' => 'Name', 'horizontal_align' => 'left', 'data_type' => 'string'),
                    array('index' => 'C', 'name' => 'SKU', 'data_type' => 'string'),
                    array('index' => 'D', 'name' => 'Stock Total', 'horizontal_align' => 'right', 'data_type' => 'string'),
                    array('index' => 'E', 'name' => 'Stock Reserved', 'horizontal_align' => 'right', 'data_type' => 'string'),
                );
                $file_name = 'out_of_stock_products_' . date('mdY') . '.xlsx';
                $res = app()->XService->run('Shop.Common.exportToExcel', array(
                    'columns' => $columns,
                    'data' => $data,
                    'file_name' => $file_name,
                    'excel_sheet_title' => 'Out of stock products',
                ));
            } elseif ($export_type == 'pdf') {
                $grid_content = $this->renderPartial('_out_of_stock_products_report_grid', array('data' => $data), true);
                $file_name = 'out_of_stock_products_' . date('mdY') . '.pdf';

                /*Yii::import('Shop.components.WKHtmlToPdf');
                try {
                    $wkhtmltopdf = new WKHtmlToPdf(array(
                        'binpath' => '/usr/local/bin/',
                        'tmppath' => Yii::getPathOfAlias('site') . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'assets',
                        'html' => $grid_content,
                    ));
                    $wkhtmltopdf->output(wkhtmltopdf::MODE_DOWNLOAD, $file_name);
                } catch (Exception $e) {
                    echo $e->getMessage();
                }*/

                $res = app()->XService->run('Shop.Common.exportToPDF', array(
                    'content' => $grid_content,
                    'file_name' => $file_name,
                    //'library' => 'mpdf',
                ));
            }
        }
    }

    public function actionSaleAvailableProductsReport()
    {
        $model = new Product('search');
        $model->unsetAttributes(); // clear any default values
        $model->status = '1';
        $model->in_stock = '1';

        if (isset($_GET['Product'])) {
            $model->attributes = $_GET['Product'];
        }

        $this->render('sale_available_products_report', array(
            'model' => $model,
        ));
    }

    public function actionExportSaleAvailableProductsReport()
    {
        if (app()->request->isPostRequest) {
            $export_type = isset($_POST['export-to-excel']) ? 'excel' : 'pdf';
            $data = array();
            $limit = 100;
            $stop = false;
            $offset = 0;
            while ($stop == false) {
                $sql = '
                SELECT t.id, t.name FROM "' . SITE_ID . '_shop_product" "t" WHERE t.status = true AND t.in_stock = true
                AND ( (NOW() >= t.available_start_date AND NOT t.available_start_date IS NULL) OR t.available_start_date IS NULL)
                AND ( (NOW() <= t.available_end_date AND NOT t.available_end_date IS NULL) OR t.available_end_date IS NULL)
                ORDER BY t.id DESC LIMIT ' . $limit . ' OFFSET ' . $offset;
                $products = app()->db->createCommand($sql)->queryAll();
                if (!is_array($products) || count($products) <= 0) {
                    $stop = true;
                } else {
                    foreach ($products as $product) {
                        $row = array();
                        // get categories of this product
                        $cats = array();
                        $cat_sql = '
                        SELECT c.title FROM "' . SITE_ID . '_shop_category" "c"
                        INNER JOIN "' . SITE_ID . '_shop_product_category" "pc" ON pc.category_id = c.id
                        WHERE pc.product_id = ' . $product['id'];
                        $cats_rows = app()->db->createCommand($cat_sql)->queryAll();
                        if (is_array($cats_rows) && count($cats_rows) > 0) {
                            foreach ($cats_rows as $cat_row) {
                                $cats[] = $cat_row['title'];
                            }
                        }
                        if ($export_type == 'excel') {
                            $row['A'] = implode(', ', $cats);
                            // name
                            $row['B'] = $product['name'];
                        } elseif ($export_type == 'pdf') {
                            $row['cats'] = implode(', ', $cats);
                            // name
                            $row['name'] = $product['name'];
                        }

                        // get sub products of this product for sku, stock
                        $sku_str = $stock_total_str = $stock_reserved_str = $qoh_str = '';
                        $sub_sql = 'SELECT sku, stock_total, stock_reserved FROM "' . SITE_ID . '_shop_subproduct" WHERE product_id = ' . $product['id'];
                        $sub_rows = app()->db->createCommand($sub_sql)->queryAll();
                        if (is_array($sub_rows) && count($sub_rows) > 0) {
                            foreach ($sub_rows as $sub_row) {
                                if ($export_type == 'excel') {
                                    $sku_str .= $sub_row['sku'] . "\n";
                                } else {
                                    $sku_str .= '<p>' . $sub_row['sku'] . '</p>';
                                }
                                $stock_total = intval($sub_row['stock_total']);
                                $stock_reserved = intval($sub_row['stock_reserved']);
                                if ($export_type == 'excel') {
                                    $stock_total_str .= $stock_total . "\n";
                                } else {
                                    $stock_total_str .= '<p>' . $stock_total . '</p>';
                                }
                                if ($export_type == 'excel') {
                                    $stock_reserved_str .= $stock_reserved . "\n";
                                } else {
                                    $stock_reserved_str .= '<p>' . $stock_reserved . '</p>';
                                }
                                if ($export_type == 'excel') {
                                    $qoh_str .= ($stock_total - $stock_reserved) . "\n";
                                } else {
                                    $qoh_str .= '<p>' . ($stock_total - $stock_reserved) . '</p>';
                                }
                            }
                        }
                        if ($export_type == 'excel') {
                            $row['C'] = $sku_str;
                            $row['D'] = $stock_total_str;
                            $row['E'] = $stock_reserved_str;
                            $row['F'] = $qoh_str;
                        } elseif ($export_type == 'pdf') {
                            $row['sku'] = $sku_str;
                            $row['stock_total'] = $stock_total_str;
                            $row['stock_reserved'] = $stock_reserved_str;
                            $row['qoh'] = $qoh_str;
                        }

                        $data[] = $row;
                    }
                }
                $offset = $offset + $limit;
            }
            // export
            if ($export_type == 'excel') {
                $columns = array(
                    array('index' => 'A', 'name' => 'Categories'),
                    array('index' => 'B', 'name' => 'Name', 'horizontal_align' => 'left', 'data_type' => 'string'),
                    array('index' => 'C', 'name' => 'SKU', 'data_type' => 'string'),
                    array('index' => 'D', 'name' => 'Stock Total', 'horizontal_align' => 'right', 'data_type' => 'string'),
                    array('index' => 'E', 'name' => 'Stock Reserved', 'horizontal_align' => 'right', 'data_type' => 'string'),
                    array('index' => 'F', 'name' => 'Quantity On Hand', 'horizontal_align' => 'right', 'data_type' => 'string'),
                );
                $file_name = 'sale_available_products_' . date('mdY') . '.xlsx';
                $res = app()->XService->run('Shop.Common.exportToExcel', array(
                    'columns' => $columns,
                    'data' => $data,
                    'file_name' => $file_name,
                    'excel_sheet_title' => 'Sale available products',
                ));
            } elseif ($export_type == 'pdf') {
                $grid_content = $this->renderPartial('_sale_available_products_report_grid', array('data' => $data), true);
                $file_name = 'sale_available_products_' . date('mdY') . '.pdf';

                /*Yii::import('Shop.components.WKHtmlToPdf');
                try {
                    $wkhtmltopdf = new WKHtmlToPdf(array(
                        'binpath' => '/usr/local/bin/',
                        'tmppath' => Yii::getPathOfAlias('site') . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'assets',
                        'html' => $grid_content,
                    ));
                    $wkhtmltopdf->output(wkhtmltopdf::MODE_DOWNLOAD, $file_name);
                } catch (Exception $e) {
                    echo $e->getMessage();
                }*/

                $res = app()->XService->run('Shop.Common.exportToPDF', array(
                    'content' => $grid_content,
                    'file_name' => $file_name,
                    //'library' => 'mpdf',
                ));
            }
        }
    }

    public function actionImport()
    {
        set_time_limit(0);
        $action = Yii::app()->request->getPost('action', '');
        if (empty($action)) {
            $action = Yii::app()->request->getQuery('action', 'upload');
        }
        $action = strtolower($action);
        $file = '';
        $errors = NULL;
        $categories = array();
        $total = 0;
        switch ($action) {
            case 'upload':
                if (isset($_POST['action'])) {
                    /** @var $uploaded CUploadedFile */
                    $uploaded = CUploadedFile::getInstanceByName('file');
                    if (is_object($uploaded)) {
                        //validate ext file
                        if (!in_array($uploaded->getExtensionName(), array('xls', 'xlsx', 'csv'))) {
                            $errors = array('Invalid file extensions. Only allow: xls, xlsx, csv file.');
                        } elseif ($uploaded->saveAs(app()->XService->CachePath . DIRECTORY_SEPARATOR . $uploaded->getName())) {
                            $file = $uploaded->getName();
                            $results = $this->api('Shop.Product.import', array(
                                'file' => app()->XService->CachePath . DIRECTORY_SEPARATOR . $uploaded->getName(),
                            ));
                            if (isset($results['error'])) {
                                $errors = $results['error'];
                            }
                            if (isset($results['categories'])) {
                                $categories = $results['categories'];
                            }
                            if (isset($results['total'])) {
                                $total = $results['total'];
                            }
                            $action = 'import';
                        } else {
                            $errors = array('Can not upload file. Please, try again.');
                        }
                    } else {
                        $errors = array('Choose file to upload.');
                    }
                } else {
                    if (Yii::app()->user->hasFlash('errors')) {
                        $errors = Yii::app()->user->getFlash('errors');
                    }
                }
                break;
            case 'import':
                if (isset($_POST['action'])) {
                    $file = $_POST['file'];
                    //validate
                    $results = $this->api('Shop.Product.import', array(
                        'file' => app()->XService->CachePath . DIRECTORY_SEPARATOR . $file,
                        'validateOnly' => false,
                        'fields' => $_POST,
                        'skipDuplicated' => $this->post('skip', false),
                    ));
                    if (Yii::app()->XService->hasErrors('Shop.Product.import')) {
                        $errors = $results['error'];
                    } else {
                        $this->render('import_success', array(
                            'categories' => $results['categories'],
                            'products' => $results['total'],
                            'importImages' => isset($results['importImages']) ? $results['importImages'] : false,
                            'file' => $file,
                        ));
                        Yii::app()->end();
                    }
                }
                break;
            case 'import_image':
                $file = $_POST['file'];
                $results = $this->api('Shop.Product.import', array(
                    'file' => app()->XService->CachePath . DIRECTORY_SEPARATOR . $file,
                    'validateOnly' => false,
                    'processImage' => true,
                ));

                if (Yii::app()->XService->hasErrors('Shop.Product.import')) {
                    $errors = $results['error'];
                } elseif (isset($_POST['import_image'])) {
                    $this->render('import_images_success', array(
                        'products' => $results['total'],
                    ));
                }
                break;
        }
        $this->render('import', array(
            'action' => $action,
            'file' => $file,
            'errors' => $errors,
            'categories' => $categories,
            'total' => $total,
            'lastColumn' => isset($results, $results['lastColumn']) ? $results['lastColumn'] : 0,
            'lastRow' => isset($results, $results['lastRow']) ? $results['lastRow'] : 0,
        ));
    }

    public function actionImportPrice()
    {
        set_time_limit(0);
        $action = Yii::app()->request->getPost('action', '');
        if (empty($action)) {
            $action = Yii::app()->request->getQuery('action', 'upload');
        }
        $action = strtolower($action);
        $file = '';
        $errors = NULL;
        $total = 0;
        switch ($action) {
            case 'upload':
                if (isset($_POST['action'])) {
                    /** @var $uploaded CUploadedFile */
                    $uploaded = CUploadedFile::getInstanceByName('file');
                    if (is_object($uploaded)) {
                        //validate ext file
                        if (!in_array($uploaded->getExtensionName(), array('xls', 'xlsx', 'csv'))) {
                            $errors = array('Invalid file extensions. Only allow: xls, xlsx, csv file.');
                        } elseif ($uploaded->saveAs(app()->XService->CachePath . DIRECTORY_SEPARATOR . $uploaded->getName())) {
                            $file = $uploaded->getName();
                            $results = $this->api('Shop.Product.importPrice', array(
                                'file' => app()->XService->CachePath . DIRECTORY_SEPARATOR . $uploaded->getName(),
                            ));
                            if (isset($results['error'])) {
                                $errors = $results['error'];
                            }
                            if (isset($results['total'])) {
                                $total = $results['total'];
                            }
                            $action = 'import';
                        } else {
                            $errors = array('Can not upload file. Please, try again.');
                        }
                    } else {
                        $errors = array('Choose file to upload.');
                    }
                } else {
                    if (Yii::app()->user->hasFlash('errors')) {
                        $errors = Yii::app()->user->getFlash('errors');
                    }
                }
                break;
            case 'import':
                if (isset($_POST['action'])) {
                    $file = $_POST['file'];
                    //validate
                    $results = $this->api('Shop.Product.importPrice', array(
                        'file' => app()->XService->CachePath . DIRECTORY_SEPARATOR . $file,
                        'validateOnly' => false,
                        'fields' => $_POST,
                        'skipDuplicated' => true,
                    ));
                    if (Yii::app()->XService->hasErrors('Shop.Product.importPrice')) {
                        $errors = $results['error'];
                    } else {
                        $this->render('importPrice_success', array(
                            'products' => $results['total'],
                            'file' => $file,
                        ));
                        Yii::app()->end();
                    }
                }
                break;
        }
        $this->render('importPrice', array(
            'action' => $action,
            'file' => $file,
            'errors' => $errors,
            'total' => $total,
            'lastColumn' => isset($results, $results['lastColumn']) ? $results['lastColumn'] : 0,
            'lastRow' => isset($results, $results['lastRow']) ? $results['lastRow'] : 0,
        ));
    }

    public function getAttributeGroupsForNewSubproduct()
    {
        //build the attribute array
        $attribute_data = array();
        $groups = AttributeGroup::model()->findAllByAttributes(array(
            'is_sub' => true,
            'status' => true,
            'required' => true,
        ));
        foreach ($groups as $group) {
            if (isset($attribute_data[$group->id])) {
                continue;
            }
            $attrs = $group->attr(array(
                'condition' => 'status=:status',
                'params' => array(
                    ':status' => true
                ),
                'order' => "attr_attr.ordering, trim(name)"
            ));
            if (is_array($attrs) && count($attrs) > 0) {
                $attribute_data[$group->id] = array(
                    'name' => $group->name,
                    'type' => $group->type,
                    'data' => CHtml::listData($attrs, 'id', 'name'));
            }
        }

        return $attribute_data;
    }

    //Sub function
    public function getAttributesSubproduct($model, $productId)
    {
        //Find all attribute groups relate to this product
        $product = Product::model()->findByPk($productId);
        if (!is_object($product))
            return array();

        //build the attribute array
        $attribute_data = array();
        if ($model->isNewRecord) {
            $groups = AttributeGroup::model()->findAllByAttributes(array(
                'is_sub' => true,
                'status' => true,
                'required' => true,
            ));
            if (!is_array($groups)) $groups = array();
            $product_groups = $product->attribute_groups(array('condition' => 'attribute_groups.is_sub=true AND attribute_groups.status=true'));
            foreach ($product_groups as $product_group)
                $groups[] = $product_group;
            unset($product_groups);
        } else
            $groups = $product->attribute_groups(array('condition' => 'attribute_groups.is_sub=true AND attribute_groups.status=true'));
        foreach ($groups as $group) {
            if (isset($attribute_data[$group->id])) continue;
            $attrs = $group->attr(array(
                'condition' => 'status=:status',
                'params' => array(
                    ':status' => true
                ),
                'order' => "attr_attr.ordering, trim(name)"
            ));
            if (is_array($attrs) && count($attrs) > 0) {
                $attribute_data[$group->id] = array(
                    'name' => $group->name,
                    'type' => $group->type,
                    'data' => CHtml::listData($attrs, 'id', 'name'));
            }
        }
        return $attribute_data;
    }

    public function getSelectedAttributesSubproduct($model, $group_id)
    {
        $command = Yii::app()->db->createCommand();
        $rows = $command->select('attribute_id')
            ->from(SITE_ID . '_shop_subproduct_attribute')
            ->where('subproduct_id=:subproduct_id AND group_id=:group_id', array(
                ':subproduct_id' => $model->id,
                'group_id' => $group_id
            ))->queryAll();
        $selected = array();
        if (is_array($rows) && count($rows)) {
            foreach ($rows as $row) {
                foreach ($row as $value)
                    $selected[] = $value;
            }
        }
        return $selected;
    }

    /**
     * Set on sale for subproducts
     *
     * @author: HAU DAI
     */
    public function actionSetOnSale()
    {
        if (Yii::app()->request->isPostRequest) {
            if (isset($_POST['productIds']) && isset($_POST['on_sale_start'])) {
                //Check subIds are not empty value
                $productIds = array_filter(explode(',', $_POST['productIds']));
                if (count($productIds) > 0) {
                    //Change format datetime to save into db
                    $start_date = date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $_POST['on_sale_start'])));
                    if (isset($_POST['on_sale_end']) && $_POST['on_sale_end'] != '')
                        $end_date = date('Y-m-d H:i:s', strtotime(str_replace('/', '-', $_POST['on_sale_end']) . ' 23:59:00'));
                    else
                        $end_date = null;
                    //Update on-sale product
                    Yii::app()->db->createCommand()->update(SITE_ID . '_shop_product', array(
                        'on_sale' => true,
                        'on_sale_start' => $start_date,
                        'on_sale_end' => $end_date,
                    ), 'id IN (' . implode(',', $productIds) . ')', array());
                    //Update all subproduct for each product
                    $this->api('Shop.Product.setOnSaleAllSubs', array('productIds' => $productIds));
                }
            }
        } else {
            //Render edit form
            if (isset($_GET['id'])) {
                $this->render('set_on_sale', array(
                    'productIds' => $_GET['id']
                ));
            }
        }
    }

    /**
     * Show pop up for subproducts admin
     *
     * @return mixed
     *
     * @author HAU DAI
     */
    public function actionSubproductsAdmin()
    {
        if (isset($_GET['productId']) && isset($_GET['productName'])) {
            $subProduct = new SubProduct('search');
            $subProduct->unsetAttributes();
            if (isset($_GET['SubProduct'])) {
                $subProduct->attributes = $_GET['SubProduct'];
            }
            $subProduct->product_id = $_GET['productId'];
            $productName = $_GET['productName'];
            $this->layout = '//layouts/popup1';
            return $this->render('_subproduct_admin', array(
                'model' => $subProduct,
                'productName' => $productName,
                'lazyLoad' => false
            ));
        }
    }

    /**
     * Set default subproduct for product
     *
     * @author HAU DAI
     */
    public function actionSetDefaultSubproduct()
    {
        if (Yii::app()->request->isPostRequest) {
            $subId = $this->get('subId', 0);
            $productId = $this->get('productId', 0);
            if ($subId && $productId) {
                Product::model()->updateByPk($productId, array(
                    'sub_default' => $subId,
                ));
            }
        }
    }
}
